const log = require('./util/log'),
  getHtml = require('./util/getHtml'),
  chromeMng = require('./mng/chromeMng.20180824'),
  httpPort = 10003;

var tasks = {}

require('http').createServer((req, res) => {
  require('./util/service').handleBusPost(req, res, reqObj => {
    new Promise(resolve => {
      // log('收到任务', reqObj)
      if (!!tasks[reqObj.uuid]) {
        resolve({
          result: -1,
          msg: 'uuid重复'
        })
        return
      }
      if (!chromeMng.client) {
        resolve({
          uuid: reqObj.uuid,
          result: -1,
          msg: '连不上chrome'
        })
        return
      }
      if (chromeMng.busy) {
        resolve({
          uuid: reqObj.uuid,
          result: -1,
          msg: 'chrome忙'
        })
        return
      }
      chromeMng.busy = true
      resolve({
        result: 1
      })
      new Promise(async resolve => {
        // log('开始任务', reqObj)
        tasks[reqObj.uuid] = reqObj
        chromeMng.getHtml({
          url: reqObj.data.url
        }).then(html => {
          resolve({
            uuid: reqObj.uuid,
            result: 1,
            data: html
          })
          chromeMng.busy = false
        })
      }).then(resObj => {
        getHtml(resStr => {
        }, () => {
        }, 'http://127.0.0.1:10000', JSON.stringify(resObj))
        resObj.data = '...'
        // log('完成任务', resObj)
        delete tasks[reqObj.uuid]
      })
    }).then(resObj => {
      // log('回复任务', resObj)
      res.end(JSON.stringify(resObj))
    })
  })
}).listen(httpPort, () => {
  log('http listening ' + httpPort)
})

// getHtml(resStr => {
// }, err => {
// }, 'http://127.0.0.1:10003', JSON.stringify({
//   uuid: '1',
//   data: {
//     url: 'https://zoro.site'
//   }
// }))
